import axios from 'axios';
import { API_CONFIG, checkApiKey } from '../config/api';

// 创建 Moonshot API 实例
const moonshotInstance = axios.create({
  baseURL: API_CONFIG.MOONSHOT.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    'Authorization': `Bearer ${API_CONFIG.MOONSHOT.API_KEY}`,
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
moonshotInstance.interceptors.request.use(
  (config) => {
    console.log('发送 Moonshot API 请求:', config.url);
    return config;
  },
  (error) => {
    console.error('Moonshot API 请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
moonshotInstance.interceptors.response.use(
  (response) => {
    console.log('Moonshot API 响应:', response.data);
    return response.data;
  },
  (error) => {
    console.error('Moonshot API 响应错误:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

// 聊天消息接口
export interface ChatMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

// 聊天请求参数
export interface ChatRequest {
  model: string;
  messages: ChatMessage[];
  temperature?: number;
  max_tokens?: number;
  stream?: boolean;
}

// 聊天响应
export interface ChatResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: {
      role: string;
      content: string;
    };
    finish_reason: string;
  }>;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

// 发送聊天消息到 Moonshot API
export const sendChatMessage = async (
  messages: ChatMessage[],
  options?: {
    model?: string;
    temperature?: number;
    max_tokens?: number;
  }
): Promise<ChatResponse> => {
  try {
    // 检查API密钥是否配置
    if (!checkApiKey()) {
      throw new Error('API密钥未配置，请检查环境变量 VITE_MOONSHOT_API_KEY');
    }

    const requestData: ChatRequest = {
      model: options?.model || API_CONFIG.MOONSHOT.DEFAULT_MODEL,
      messages,
      temperature: options?.temperature || API_CONFIG.MOONSHOT.DEFAULT_TEMPERATURE,
      max_tokens: options?.max_tokens || API_CONFIG.MOONSHOT.DEFAULT_MAX_TOKENS,
      stream: false,
    };

    const response = await moonshotInstance.post('/v1/chat/completions', requestData);
    return response;
  } catch (error) {
    console.error('发送聊天消息失败:', error);
    
    // 提供更友好的错误信息
    if (axios.isAxiosError(error)) {
      if (error.response?.status === 401) {
        throw new Error('API密钥无效,请检查配置');
      } else if (error.response?.status === 429) {
        throw new Error('API调用频率超限,请稍后再试');
      } else if (error.response?.status >= 500) {
        throw new Error('服务器错误，请稍后再试');
      }
    }
    
    throw error;
  }
};

// 获取可用模型列表
export const getModels = async () => {
  try {
    const response = await moonshotInstance.get('/v1/models');
    return response;
  } catch (error) {
    console.error('获取模型列表失败:', error);
    throw error;
  }
};

// 健康检查
export const healthCheck = async () => {
  try {
    const response = await moonshotInstance.get('/v1/models');
    return response.data ? true : false;
  } catch (error) {
    console.error('Moonshot API 健康检查失败:', error);
    return false;
  }
};

export default moonshotInstance;
